package com.huaxin.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.device.dto.ResponseCode;
import com.huaxin.device.dto.ResponseResult;
import com.huaxin.device.dto.request.EquipmentConnectionsCreateReqDTO;
import com.huaxin.device.dto.request.EquipmentConnectionsPageListReqDTO;
import com.huaxin.device.dto.request.EquipmentConnectionsUpdateReqDTO;
import com.huaxin.device.mapper.EquipmentConnectionsMapper;
import com.huaxin.device.mapping.EquipmentConnectionsMapping;
import com.huaxin.device.models.EquipmentConnection;
import com.huaxin.device.service.EquipmentConnectionsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.webjars.NotFoundException;

import static org.springframework.util.StringUtils.hasText;

@Service
@RequiredArgsConstructor
public class EquipmentConnectionsServiceImpl extends ServiceImpl<EquipmentConnectionsMapper, EquipmentConnection> implements EquipmentConnectionsService {

    private final ApplicationContext applicationContext;
    private final EquipmentConnectionsMapping mapping;

    @Override
    public ResponseResult<EquipmentConnection> create(EquipmentConnectionsCreateReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数不能为空");
        }

        EquipmentConnection entity = mapping.toEntity(in);
        if (!save(entity)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "创建失败，请稍后再试", null);
        }
        EquipmentConnection created = getById(entity.getId());
        return ResponseResult.ok(created);
    }

    @Override
    public EquipmentConnection getByConnectionId(String id) {
        if (!hasText(id)) {
            throw new IllegalArgumentException("ID不能为空");
        }
        EquipmentConnection entity = getById(id);
        if (entity == null) {
            throw new NotFoundException("设备连接关系不存在");
        }
        return entity;
    }

    @Override
    public ResponseResult<String> update(EquipmentConnectionsUpdateReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数不能为空");
        }

        EquipmentConnection entity = getByConnectionId(in.getId());

        mapping.updateEntity(in, entity);
        if (!updateById(entity)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "更新失败，请稍后再试", null);
        }
        return ResponseResult.ok("更新成功");
    }

    @Override
    public ResponseResult<String> delete(String id) {
        EquipmentConnection entity = getByConnectionId(id);
        
        boolean removed = this.applicationContext.getBean(EquipmentConnectionsServiceImpl.class).removeById(id);
        if (!removed) {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "删除失败，请稍后重试", null);
        }
        return ResponseResult.ok("删除成功");
    }

    @Override
    public ResponseResult<IPage<EquipmentConnection>> pageQuery(EquipmentConnectionsPageListReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数不能为空");
        }

        IPage<EquipmentConnection> page = new Page<>(in.getPageNum(), in.getPageSize());
        LambdaQueryWrapper<EquipmentConnection> wrapper = new LambdaQueryWrapper<>();

        // 起点设备类型
        if (hasText(in.getFromEquipmentType())) {
            wrapper.eq(EquipmentConnection::getFromEquipmentType, in.getFromEquipmentType());
        }

        // 终点设备类型
        if (hasText(in.getToEquipmentType())) {
            wrapper.eq(EquipmentConnection::getToEquipmentType, in.getToEquipmentType());
        }

        // 连接类型
        if (hasText(in.getConnectionType())) {
            wrapper.eq(EquipmentConnection::getConnectionType, in.getConnectionType());
        }

        // 关键词搜索：连接名称或备注
        if (hasText(in.getKeyword())) {
            wrapper.and(wrapper1 -> wrapper1
                    .like(EquipmentConnection::getConnectionName, in.getKeyword())
                    .or()
                    .like(EquipmentConnection::getNotes, in.getKeyword()));
        }

        // 按创建时间降序
        wrapper.orderByDesc(EquipmentConnection::getCreatedAt);

        IPage<EquipmentConnection> resultPage = this.page(page, wrapper);
        return ResponseResult.ok(resultPage);
    }
}